package shopping;

import java.sql.SQLException;

import jdbc.JDBCUtils;
import mybeans.Beans;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

public class Add2CartService {

	public int add2Cart(String userID, String goodsID, String buyNum) {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDs());
		String sql;
		if(hasGoodsIDInMyGoods(goodsID, userID)){
			sql = "update MyGoods set buyNum = buyNum + ? where goodsID = ? and userID = ?";
			try {
				return qr.update(sql, buyNum, goodsID, userID);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			sql = "insert into MyGoods (userID, goodsID, buyNum) values(?, ?, ?)";
			try {
				return qr.update(sql, userID, goodsID, buyNum);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		;
		return 0;
	}

	private boolean hasGoodsIDInMyGoods(String goodsID, String userID) {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDs());
		String sql = "select *from MyGoods where goodsID = ? and userID = ?";
		String[] param = new String[]{
				goodsID, userID
		};
		try {
			if(qr.query(sql, param, new BeanHandler<>(Beans.class))!=null){
				return true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

}
